package com.example.common.tools;


import com.example.common.entity.UserInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class UserSessionUtils {

    /**
     * 通过 Session 获取用户信息
     * @param request
     * @return
     */
    public static UserInfo getUser(HttpServletRequest request) {
        //通过 Session 获取用户信息(用户名和 id )
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppVariable.USER_SESSION_KEY) != null) {
            return (UserInfo) session.getAttribute(AppVariable.USER_SESSION_KEY);
        }
        return null;
    }

    /**
     * 修改 session 信息
     * @param request
     * @param userInfo
     * @return
     */
    public static void updateSession(HttpServletRequest request, UserInfo userInfo) {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppVariable.USER_SESSION_KEY) != null) {
            //重置 session 信息
            session.setAttribute(AppVariable.USER_SESSION_KEY, userInfo);
            System.out.println("session 数据更新!");
            return;
        }
        System.out.println("session 数据错误!");
        return;
    }

}
